<template>
  <a-modal
    :visible="visible"
    title="新增任务"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
       ref="formRef"
      :model="formState"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item ref="name" label="名称" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item ref="beanName" label="目标" name="beanName">
        <a-input v-model:value="formState.beanName" />
      </a-form-item>
      <a-form-item ref="param" label="参数" name="param">
        <a-input v-model:value="formState.param" />
      </a-form-item>
      <a-form-item ref="cronExpression" label="cron" name="cronExpression">
        <cron @onChange="(val)=>{formState.cronExpression = val}"/>
      </a-form-item>
      <a-form-item label="状态" name="enable">
        <a-switch v-model:checked="formState.enable" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="formState.remark" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
  import {message} from 'ant-design-vue';
  import {save} from "@/api/module/job";
  import {defineComponent, reactive, ref, toRaw} from "vue";
  import cron from "../cron/index";

  export default defineComponent({
    components: {
      cron
    },
    props: {
      visible: {
        type: Boolean,
      },
    },
    emit: ["close"],
    setup(props, context) {

      const formRef = ref();

      const formState = reactive({
        enable: true,
        cronExpression: "* * * * * ? *",
      });

      const formRules = {
        name: [{required: true, message: '请输入任务名称', trigger: 'blur'}],
        beanName: [{required: true, message: '请输入任务目标', trigger: 'blur'}],
        cronExpression: [{required: true, message: '请输入任务周期'}]
      };

      const saveKey = "save";

      const submit = (e) => {

        formRef.value
          .validate()
          .then(() => {
            message.loading({content: '提交中...', key: saveKey});
            save(toRaw(formState)).then((response) => {
              if (response.success) {
                message.success({content: '保存成功', key: saveKey, duration: 1}).then(() => {
                  cancel();
                });
              } else {
                message.success({content: '保存失败', key: saveKey, duration: 1}).then(() => {
                  cancel();
                });
              }
            });
          })
        .catch(error => {
          console.log('error', error);
        });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };

    return {
      submit,
      cancel,
      formRef,
      formState,
      formRules,

      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
  },
});
</script>
